package com.datastructure.test.stringjudge;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class StringJudge {

    public static void main(String[] args) {
        StringJudge stringJudge = new StringJudge();
        String s1 = "abc";
        String s2 = "cba";
        String s3 = "abcabc";
        boolean judge = stringJudge.stringJudge(s1, s2, s3);
        System.out.println(judge);
    }

    public boolean stringJudge (String s1, String s2, String s3) {
        // write code here
        String tempString = s1 + s2 +s3;
        char[] tempCharArray = tempString.toCharArray();
        char[] s3CharArray = s3.toCharArray();
        Set<Character> set = new HashSet<>();
        for (char c : tempCharArray) {
            set.add(c);
        }
        if(set.size()==1){
            return true;
        }
        StringBuilder stringBuilder = new StringBuilder(s3);
        String string = stringBuilder.reverse().toString();
        if(string.contains(s1)||string.contains(s2)){
            return false;
        }
        if(s1.length()+s2.length()!=s3.length()){
            return false;
        }
        tempString = s1 + s2;
        char[] charArray = tempString.toCharArray();
        Arrays.sort(charArray);
        tempString = new String(charArray);
        Arrays.sort(s3CharArray);
        s3 = new String(s3CharArray);
        return tempString.contains(s3);
    }

    public boolean stringJudge1 (String s1, String s2, String s3) {
        // write code here
        return s1.length() + s2.length() == s3.length() && judge(s1.toCharArray(), s2.toCharArray(), s3.toCharArray(), 0, 0);
    }

    private boolean judge(char[] s, char[] t, char[] p, int idx1, int idx2) {
        if(s.length == idx1 && t.length == idx2) {
            return true;
        }
        boolean ans = false;
        ans = ans || (idx1 < s.length && s[idx1] == p[idx1+idx2] && judge(s, t, p, idx1+1, idx2));
        ans = ans || (idx2 < t.length && t[idx2] == p[idx1+idx2] && judge(s, t, p, idx1, idx2+1));
        return ans;
    }
}
